package com.ruoyi.web.controller.project;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.domain.entity.*;
import com.ruoyi.project.domain.query.ProjectFeeQuery;
import com.ruoyi.project.domain.query.ProjectQuery;
import com.ruoyi.project.service.*;
import com.ruoyi.system.service.ISysDictDataService;
import io.swagger.annotations.ApiOperation;
import org.apache.xmlbeans.impl.xb.xsdschema.All;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/project/allocationDetail")
public class AllocationDetailController {


    @Resource
    private IProjectAllocationDetailService detailService;

    @Resource
    private IProjectParticipanService personService;

    @Resource
    private IProjectAllocationService allocationService;

    @Resource
    private ISysDictDataService dictDataService;

    @Resource
    private IProjectService projectService;

    @Resource
    private IProjectPhaseService phaseService;


    @ApiOperation("修改")
    @PutMapping
    public R updateAllocationDetail(@RequestBody AllocationDetail detail) {
        //查询设置audit 总经理 或者 项目经理 销售负责人
        Long userId = SecurityUtils.getUserId();

        //如果是验收中进来的 验收还没有项目提成 不用设置金额
        Boolean flag = false;
        String projectNo = detail.getProjectNo();
        LambdaQueryWrapper<ProjectPhase> phaseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        phaseLambdaQueryWrapper.eq(ProjectPhase::getProjectNo, projectNo);
        phaseLambdaQueryWrapper.eq(ProjectPhase::getPhaseId, "5");//如果有了核算信息
        List<ProjectPhase> phaseList = phaseService.list(phaseLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(phaseList)) {
            //是验收环节
            flag = true;
        }

        //如果是销售负责人 特殊处理  只更改提交的信息
        //查询父项  是否是销售负责人
        // 更新的时候同步更新质保金绩效的
        Long allocationId = detail.getAllocationId();

        //查询质保阶段对应的参与人
        LambdaQueryWrapper<AllocationDetail> updateDetailWrapper = new LambdaQueryWrapper<AllocationDetail>();
        updateDetailWrapper.eq(AllocationDetail::getProjectNo, detail.getProjectNo());
        updateDetailWrapper.eq(AllocationDetail::getCurrent, "2");
        updateDetailWrapper.eq(AllocationDetail::getPersonName, detail.getPersonName());
        updateDetailWrapper.eq(AllocationDetail::getAllocationId, detail.getAllocationId());

        ProjectAllocation allocationById = allocationService.getById(allocationId);
        if (allocationById.getPostId() == 5L) {
            //只有总经理能够确认销售负责人的绩效
            //这里说明是总经理操作
            List<Integer> auditPer = detail.getAudit();
            if (auditPer == null || auditPer.size() == 0) {
                auditPer = new ArrayList<>();
            }
            if (userId.equals(100L)) {
                auditPer.add(100);
            }
            try {
                AllocationDetail one = detailService.getOne(updateDetailWrapper);
                one.setRatio(detail.getRatio());
                one.setAudit(auditPer);
                detailService.updateById(one);

                //多个销售负责人 处理其他销售负责人的
                if (flag == false || checkSaleProject(allocationById, projectNo, one)) {
                    setSaleRatio(detail, one);
                }

            } catch (Exception e) {
                throw new RuntimeException("后端接口出错,请联系管理员");
            }
            detail.setAudit(auditPer);
            return R.ok(detailService.updateById(detail));
        }
        // 如果不是总经理触发这个方法  查询是否已经被总经理确认了 如果确认了 就提示不能再改了
        if (!userId.equals(100L)) {
            AllocationDetail detailById = detailService.getById(detail.getId());
            List<Integer> auditPer = detailById.getAudit();
            if (auditPer == null || auditPer.size() == 0) {
                auditPer = new ArrayList<>();
            }
            if (auditPer.contains(100)) {
                // 包含 100
                throw new RuntimeException("总经理已确认,无法再次更改");
            }
        }


        //如果是总经理
        if (userId.equals(100L)) {
            List<Integer> audit = detail.getAudit();
            if (audit != null && !audit.isEmpty()) {
                audit.add(100);
            } else {
                audit = new ArrayList<>();
                audit.add(100);
            }
            detail.setAudit(audit);

            try {
                AllocationDetail one = detailService.getOne(updateDetailWrapper);
                one.setRatio(detail.getRatio());
                //获取质保金的总提成
                BigDecimal allocationMoney = (allocationById.getWarrantyMoney() != null) ? allocationById.getWarrantyMoney() : BigDecimal.ZERO;
                BigDecimal performanceBonus = allocationMoney
                        .multiply(one.getRatio())       // allCommission * ratio
                        .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                one.setMoney(performanceBonus);

                //设置个人绩效
                String personAllocation = dictDataService.selectDictLabel("allocation_type", "1");
                BigDecimal personAllocationMoney = performanceBonus.multiply(new BigDecimal(personAllocation));
                one.setPersonMoney(personAllocationMoney);

                //设置部门绩效
                String deptAllocation = dictDataService.selectDictLabel("allocation_type", "2");
                BigDecimal deptAllocationMoney = performanceBonus.multiply(new BigDecimal(deptAllocation));
                one.setDeptMoney(deptAllocationMoney);


                //设置个人绩效和部门绩效

                one.setAudit(audit);
                detailService.updateById(one);
            } catch (Exception e) {
                throw new RuntimeException("后端接口出错,请联系管理员");
            }

        } else {
            //查询是否是项目经理或销售负责人
            LambdaQueryWrapper<ProjectParticipan> personWrapper = new LambdaQueryWrapper<ProjectParticipan>();
            personWrapper.eq(ProjectParticipan::getProjectNo, detail.getProjectNo());
            personWrapper.eq(ProjectParticipan::getParticipantId, userId);
            List<ProjectParticipan> list = personService.list(personWrapper);
            List<Integer> auditPost = new ArrayList<>();
            for (ProjectParticipan person : list) {
                //如果id匹配上
                if (person.getParticipantId().equals(userId)) {
                    //取出岗位id
                    Long postId = person.getPostId();
                    auditPost.add(postId.intValue());
                }
            }
            if (detail.getAudit() != null && !detail.getAudit().isEmpty()) {
                auditPost.addAll(detail.getAudit());
            }
            detail.setAudit(auditPost);

            try {//更新质保阶段的
                AllocationDetail one = detailService.getOne(updateDetailWrapper);
                BigDecimal allocationMoney = (allocationById.getWarrantyMoney() != null) ? allocationById.getWarrantyMoney() : BigDecimal.ZERO;
                BigDecimal performanceBonus = allocationMoney
                        .multiply(one.getRatio())       // allCommission * ratio
                        .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                one.setMoney(performanceBonus);

                //设置个人绩效
                String personAllocation = dictDataService.selectDictLabel("allocation_type", "1");
                BigDecimal personAllocationMoney = performanceBonus.multiply(new BigDecimal(personAllocation));
                one.setPersonMoney(personAllocationMoney);

                //设置部门绩效
                String deptAllocation = dictDataService.selectDictLabel("allocation_type", "2");
                BigDecimal deptAllocationMoney = performanceBonus.multiply(new BigDecimal(deptAllocation));
                one.setDeptMoney(deptAllocationMoney);

                one.setRatio(detail.getRatio());
                one.setAudit(auditPost);
                detailService.updateById(one);
            } catch (Exception e) {
                throw new RuntimeException("后端接口出错,请联系管理员");
            }

        }
        boolean result = detailService.updateAllocationDetail(detail, flag);
        if (flag) {
            return R.ok();
        }
        detailService.setSaleMoney(detail.getProjectNo(), detail.getCurrent());
        return R.ok(result);
    }

    //多个销售负责人  设置比例 计算金额 第一个参数为当前的 第二个为质保阶段的
    public void setSaleRatio(AllocationDetail allocationDetail, AllocationDetail warrantyDetail) {
        //查询其它销售负责人
        LambdaQueryWrapper<AllocationDetail> detailWrapper = new LambdaQueryWrapper<AllocationDetail>();
        detailWrapper.eq(AllocationDetail::getAllocationId, allocationDetail.getAllocationId());
        detailWrapper.eq(AllocationDetail::getCurrent, allocationDetail.getCurrent());
        //排除当前的
        detailWrapper.ne(AllocationDetail::getId, allocationDetail.getId());

        //分项目提成阶段的和质保阶段的
        //这里先更新项目提成的
        List<AllocationDetail> detailList = detailService.list(detailWrapper);

        BigDecimal resultRatio = BigDecimal.ZERO;

        if (detailList != null && detailList.size() > 0) {
            BigDecimal ratio = allocationDetail.getRatio(); // 假设 ratio 是百分比，比如 30.5 表示 30.5%
            int count = detailList.size();

            // 将 100 转为 BigDecimal
            BigDecimal hundred = BigDecimal.valueOf(100);

            // 计算：(100 - ratio) / count
            BigDecimal result = hundred.subtract(ratio)
                    .divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP);

            resultRatio = result;

            for (AllocationDetail detail : detailList) {
                //应该以100为基准相加
                BigDecimal currRatio = BigDecimal.valueOf(100);
                //加上result(可能为负数) 再重新设置回对象
                BigDecimal newRatio = currRatio.add(result);
                detail.setRatio(newRatio);
                detailService.updateById(detail);
            }
            System.out.println(detailList);
        }


        //更新质保阶段的
        LambdaQueryWrapper<AllocationDetail> warrantyDetailWrapper = new LambdaQueryWrapper<AllocationDetail>();
        warrantyDetailWrapper.eq(AllocationDetail::getAllocationId, allocationDetail.getAllocationId());
        //排除已更新的
        warrantyDetailWrapper.ne(AllocationDetail::getCurrent, allocationDetail.getCurrent());
        //排除当前的
        warrantyDetailWrapper.ne(AllocationDetail::getId, allocationDetail.getId());
        //排除同一个人的
        warrantyDetailWrapper.ne(AllocationDetail::getPersonId, allocationDetail.getPersonId());
        //更新质保阶段的
        List<AllocationDetail> warrantyDetailList = detailService.list(warrantyDetailWrapper);
        for (AllocationDetail detail : warrantyDetailList) {
            //应该以100为基准相加
            BigDecimal currRatio = BigDecimal.valueOf(100);
            //加上result(可能为负数) 再重新设置回对象
            BigDecimal newRatio = currRatio.add(resultRatio);
            detail.setRatio(newRatio);
            detailService.updateById(detail);
        }

        //避免事务问题 前端重新触发
//        detailService.setSaleMoney(allocationDetail.getProjectNo(), allocationDetail.getCurrent());
    }

    public boolean checkSaleProject(ProjectAllocation allocationById, String projectNo, AllocationDetail one) {

        if (!projectNo.contains("XS")){
            return false;
        }

        //判断是否有多个销售负责人
        Boolean moreSale = false;

        if (allocationById != null) {
            Long id = allocationById.getId();
            LambdaQueryWrapper<AllocationDetail> dewrapper = new QueryWrapper<AllocationDetail>().lambda();
            dewrapper.eq(AllocationDetail::getProjectNo, projectNo);
            dewrapper.eq(AllocationDetail::getCurrent, one.getCurrent());
            dewrapper.eq(AllocationDetail::getAllocationId, id);
            List<AllocationDetail> detailList = detailService.list(dewrapper);
            Long userId = SecurityUtils.getUserId();
            if (detailList != null && detailList.size() > 1) {
                if (userId.equals(100L) || SecurityUtils.hasRole("gjadmin") || SecurityUtils.hasRole("admin")) {
                    moreSale = true;
                }
            }
        }
        return moreSale;

    }

    @PutMapping("/setSaleMoney")
    public void reSetSaleMoney(@RequestBody AllocationDetail detail) {
        detailService.setSaleMoney(detail.getProjectNo(), detail.getCurrent());
    }

    @ApiOperation("确认发放")
    @PutMapping("/confirm")
    public R allocationDetailConfirm(@RequestBody AllocationDetail detail) {
        detailService.allocationDetailConfirm(detail);
        return R.ok();
    }


    //判断该项目是否已经全部发放完成
    @GetMapping("/complete/{projectNo}")
    public void checkComplete(@PathVariable String projectNo) {
        detailService.checkComplete(projectNo);
    }


    @ApiOperation("详情")
    @GetMapping("/{id}")
    public R getDetails(@PathVariable Long id) {
        AllocationDetail detail = detailService.getById(id);
        return R.ok(detail);
    }


    @ApiOperation("获取绩效统计信息")
    @GetMapping("/statistics")
    public R getStatistics() {
//        AllocationDetail detail = detailService.getById(id);
//        return R.ok(detail);
        return null;
    }


    @ApiOperation("分页 绩效排行")
    @GetMapping(value = "/getMoneyRankPage")
    public R<TableDataInfo> getMoneyRankPage(ProjectQuery query) {
        return R.ok(detailService.getRank(query));
    }


}
